import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserRoleDto } from './dto/user-role.dto';
import { UserRoleEntity } from './entity/user-role.entity';
import * as uuid from 'uuid';
@Injectable()
export class UserRoleService {
  constructor(
    @InjectRepository(UserRoleEntity)
    private readonly userRoleRepository: Repository<UserRoleEntity>,
  ) {}

  // 关联用户和角色
  async create(userRole: UserRoleDto) {
    const { role_id, user_id } = userRole;
    const querySql = `select id FROM sys_user_role WHERE user_id='${user_id}'`;
    const queryResult = await this.userRoleRepository.query(querySql);
    // 判断用户是否关联角色，关联则先删除再新增
    if (queryResult.length > 0) {
      const deleteSql = `DELETE FROM sys_user_role WHERE user_id='${user_id}'`;
      await this.userRoleRepository.query(deleteSql);
    }
    // 新增关联数据
    const createId = uuid.v4().replace(/-/g, '');
    const saveSql = `insert into sys_user_role (id,role_id,user_id) values ('${createId}','${role_id}','${user_id}')`;
    return await this.userRoleRepository.query(saveSql);
  }

  // 根据角色id查询关联用户
  async queryUserRoleById(query) {
    const { id } = query;
    const sql = `SELECT u.id,u.username,u.nickname,u.email,u.avatar,u.update_time,u.create_time 
    FROM sys_roles AS r 
    LEFT JOIN sys_user_role AS ur ON r.id = ur.role_id
    LEFT JOIN sys_user AS u ON u.id = ur.user_id WHERE r.id='${id}' AND u.del_flag=0`;
    const data = await this.userRoleRepository.query(sql);

    return { result: data };
  }
}
